package com.backstage.interceptor;

import com.backstage.utils.MD5Utils;
import com.backstage.utils.SendMsgUtil;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;

/**
 * NAME   :  EmailSystem/com.amayadream.interceptor
 * Author :  Amayadream
 * Date   :  2015.10.06 17:33
 * TODO   :
 */
public class WeixinAppInterceptor extends HandlerInterceptorAdapter {

    private List<String> IGNORE_JOIN_WEIXIN_APP_URI;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取URI后缀
       String requestUri = request.getServletPath();
       String xToken = request.getHeader("x-token");
       String xTokenId = MD5Utils.md5("da"+ request.getHeader("x-token-id") + "quanquan.ren");
        //if(requestUri.equalsIgnoreCase("/"))   { return true; }

        //过滤不需要拦截的地址
        for (String uri : IGNORE_JOIN_WEIXIN_APP_URI) {
            if (requestUri.startsWith(uri)) {
                return true;
            }
        }

        if(!xTokenId.equals(xToken)){
            Map<String, String> returnJson = new HashedMap();
            returnJson.put("code","406");
            returnJson.put("message","登陆用户异常，请重新登陆");
            SendMsgUtil.sendJsonMessage(response,returnJson);
            return false;
        }

        return true;

    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        super.postHandle(request, response, handler, modelAndView);
    }

    public List<String> getIGNORE_JOIN_WEIXIN_APP_URI() {
        return IGNORE_JOIN_WEIXIN_APP_URI;
    }

    public void setIGNORE_JOIN_WEIXIN_APP_URI(List<String> IGNORE_JOIN_WEIXIN_APP_URI) {
        this.IGNORE_JOIN_WEIXIN_APP_URI = IGNORE_JOIN_WEIXIN_APP_URI;
    }
}
